/*package com.utils.spring;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.jetty.util.StringUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.kyhd.cpa.config.AppConfig;
import com.kyhd.cpa.controller.model.ContractRequest;
import com.kyhd.cpa.controller.model.ContractResponse;
import com.kyhd.cpa.controller.model.ContractResponse.ContractItem;
import com.kyhd.cpa.controller.model.ContractSelectList.SelectListItem;
import com.kyhd.cpa.dao.ContractRepository;
import com.kyhd.cpa.dao.model.Contract;
import com.kyhd.cpa.util.InitConst;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ContractService {
	
	@Autowired(required=true)
	AppConfig appConfig;
	
	@Autowired
	ContractRepository contractRepository;
	
	@Autowired
	DepartPlatformConstService departPlatformConstService;
	
	@Autowired
	@Qualifier("entityManager")
	EntityManager entityManager;
	
	*//**
	 * 客户/渠道下拉框列表
	 * @param contractType
	 * @return
	 *//*
	public List<SelectListItem> getNameList(Integer contractType) {
		List<SelectListItem> list = Lists.newArrayList();
		List<String> nameList = this.contractRepository.getNameList(contractType);
		for (String string : nameList) {
			SelectListItem sli = new SelectListItem();
			sli.setType(contractType);
			sli.setKey(string);
			sli.setValue(string);
			list.add(sli);
		}
		return list;	
	}
	
	*//**
	 * 试用平台列表
	 * @param type
	 * @return
	 *//*
	public List<SelectListItem> getPlatformList(Integer departType) {
		List<SelectListItem> list = Lists.newArrayList();
		List<Object[]> platformList = this.departPlatformConstService.getList(departType);
		for (Object[] obj : platformList) {
			SelectListItem sli = new SelectListItem();
			if(obj!=null&&obj[1]!=null&&obj[0]!=null) {
				sli.setType(Integer.valueOf(obj[0].toString()));
				sli.setKey(obj[1].toString());
				sli.setValue(obj[1].toString());
				list.add(sli);
			}
		}
		return list;
	}
	
	*//**
	 * 查询或者导出
	 * @param request 查询条件
	 * @param export 是否导出
	 * @return
	 *//*
	public ContractResponse query(ContractRequest request, boolean export) {
		ContractResponse response = new ContractResponse();

		int page = request.getPage();
		int limit = request.getLimit();
		String contractNo = request.getContractNo();
		Integer contractType = request.getType();
		Integer suitDepart = request.getSuitDepart();
		
		String cooperatorName = request.getCooperatorName();
		List<String> cooperatorNameList = getStrList(cooperatorName);
		
		String ownerBody = request.getOwnerBody();     
		List<String> ownerBodyList = getStrList(ownerBody);
		
		String status = request.getStatus();  
		List<Integer> statusList = getIntList(status);
		
		StringBuilder sb = new StringBuilder();
		sb.append("select * from ( select ");
		sb.append(" ct.id, ct.contract_type, ct.contract_no, ct.cooperate_no, ct.cooperator_name, ");
		sb.append(" ct.end_date, ct.owner_body, ct.owner_type, ct.pdf_path, ct.pop_mode, ");
		sb.append(" ct.remark, ct.shoulder, ct.start_date, ct.suit_depart, ct.suit_platform, ");
		sb.append(" ct.suit_product, ");
		sb.append(" (CASE WHEN 2678400 <= UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) THEN 1 ");
		sb.append(" WHEN 2592000 >= UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) and UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) > 0  THEN 0 ");
		sb.append(" WHEN UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) <= 0 THEN 3 ");
		sb.append(" ELSE 2 END) status, DATE_FORMAT(ct.createTime,'%Y-%m-%d %H:%i') createTime, ct.creator, DATE_FORMAT(ct.modifyTime,'%Y-%m-%d %H:%i') modifyTime, ");
		sb.append(" ct.modifier ");
		
		sb.append(" from contract ct where 1=1 and deleted = 0");
		if(StringUtil.isNotBlank(contractNo))
			sb.append(" and ct.contract_no like concat('%',?1,'%') ");
		if(cooperatorNameList!=null&&cooperatorNameList.size()>0)
			sb.append(" and ct.cooperator_name in (?2) ");
		if(ownerBodyList!=null&&ownerBodyList.size()>0)
			sb.append(" and ct.owner_body in (?3) ");
		if(suitDepart!=null&&suitDepart>=0)
			sb.append(" and ct.suit_depart=?4 ");
		if(contractType>0)
			sb.append(" and contract_type=?5 ");
		sb.append(" ) abc where 1=1 ");
		if(statusList!=null&&statusList.size()>0)
			sb.append(" and abc.status in (?6) ");
		
		StringBuilder order = new StringBuilder(" order by abc.status asc, abc.end_date asc ");

		List<Object[]> list = null;
		Object countObj = null;
		long count = -1;
		
		String sqlLimit = null;
		if(!export) {
			sqlLimit = sb.toString()+order.toString()
					+"limit "
					+(page-1)*limit+", "+limit+" ";
		}else {
			sqlLimit = sb.toString()+order.toString();
		}
		
		String sqlCount = "select count(1) from ("+sb.toString()+") acu";
//		log.info("sqlLimit:{}",sqlLimit);
		try {
			if(!export) {
				Query queryCount = this.entityManager.createNativeQuery(sqlCount.toString());
				if(StringUtil.isNotBlank(contractNo))
					queryCount.setParameter(1, contractNo);
				if(cooperatorNameList!=null&&cooperatorNameList.size()>0)
					queryCount.setParameter(2, cooperatorNameList);
				if(ownerBodyList!=null&&ownerBodyList.size()>0)
					queryCount.setParameter(3, ownerBodyList);
				if(suitDepart!=null&&suitDepart>=0)
					queryCount.setParameter(4, suitDepart);
				if(contractType>0)
					queryCount.setParameter(5, contractType);
				if(statusList!=null&&statusList.size()>0)
					queryCount.setParameter(6, statusList);
				
				countObj = queryCount.getSingleResult();
				count = Long.valueOf(countObj.toString());
			}
			
			Query query = this.entityManager.createNativeQuery(sqlLimit.toString());
			if(StringUtil.isNotBlank(contractNo))
				query.setParameter(1, contractNo);
			if(cooperatorNameList!=null&&cooperatorNameList.size()>0)
				query.setParameter(2, cooperatorNameList);
			if(ownerBodyList!=null&&ownerBodyList.size()>0)
				query.setParameter(3, ownerBodyList);
			if(suitDepart!=null&&suitDepart>=0)
				query.setParameter(4, suitDepart);
			if(contractType>0)
				query.setParameter(5, contractType);
			if(statusList!=null&&statusList.size()>0)
				query.setParameter(6, statusList);

			list = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		if(list==null||list.size()<=0)
			return null;
		
		List<ContractItem> itemList = Lists.newArrayList();
		for (Object[] q : list) {
			ContractItem ct = new ContractItem();
			ct.setId(Long.valueOf(q[0].toString()));
			ct.setContractNo(q[2].toString());
			ct.setContractType(Integer.valueOf(q[1].toString()));
			ct.setCooperateNo(q[3]==null?"":q[3].toString());
			ct.setCooperatorName(q[4].toString());
			ct.setOwnerBody(q[6].toString());//枚举
			ct.setOwnerType(Integer.valueOf(q[7].toString()));
			ct.setStartDate(q[12].toString());
			ct.setEndDate(q[5].toString());
			ct.setShoulder(q[11]==null?"":q[11].toString());
			ct.setStatus(Integer.valueOf(q[16].toString()));//枚举
			ct.setSuitDepart(Integer.valueOf(q[13].toString()));//枚举
			ct.setSuitPlatform(q[14]==null?"":q[14].toString());
			ct.setSuitProduct(q[15]==null?"":q[15].toString());
			ct.setPopMode(q[9]==null?"":q[9].toString());
			String pdfPath = (q[8]==null||StringUtil.isBlank(q[8].toString()))?"":appConfig.getPdfPathDomain()+q[8].toString();
			String pdfName = "".equals(pdfPath)?"":pdfPath.substring(pdfPath.lastIndexOf("/")+1, pdfPath.length());
			ct.setPdfName(pdfName);
			ct.setPdfPath(pdfPath);
			ct.setCreaterTime(q[17].toString());
			ct.setCreator(q[18]==null?"":q[18].toString());
			ct.setModifier(q[20]==null?"":q[20].toString());
			ct.setModifyTime(q[19].toString());
			ct.setRemark(q[10]==null?"":q[10].toString());
			itemList.add(ct);
		}
		
		response.setList(itemList);
		response.setTotal(count);
		return response;
	}
	
	//查看单个
	public ContractItem getById(long id) {
		ContractItem item = null;
		StringBuilder sql = new StringBuilder("select ");
		sql.append(" ct.id, ct.contract_type, ct.contract_no, ct.cooperate_no, ct.cooperator_name, ");
		sql.append(" ct.end_date, ct.owner_body, ct.owner_type, ct.pdf_path, ct.pop_mode, ");
		sql.append(" ct.remark, ct.shoulder, ct.start_date, ct.suit_depart, ct.suit_platform, ");
		sql.append(" ct.suit_product, ");
		sql.append(" (CASE WHEN 2678400 <= UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) THEN 1 ");
		sql.append(" WHEN 2592000 >= UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) and UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) > 0  THEN 0 ");
		sql.append(" WHEN UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP(now()) <= 0 THEN 3 ");
		sql.append(" ELSE 2 END) status, DATE_FORMAT(ct.createTime,'%Y-%m-%d %H:%i') createTime, ct.creator, DATE_FORMAT(ct.modifyTime,'%Y-%m-%d %H:%i') modifyTime, ");
		sql.append(" ct.modifier ");
		sql.append(" from contract ct where 1=1 and deleted = 0 and ct.id=?1 ");
		
		List<Object[]> list = null;
		try {
			Query query = this.entityManager.createNativeQuery(sql.toString());
			query.setParameter(1, id);
			
			list = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		for(Object[] obj : list) {
			item = new ContractItem();
			item.setContractNo(obj[2].toString());
			item.setContractType(Integer.valueOf(obj[1].toString()));
			item.setCooperateNo(obj[3]==null?"":obj[3].toString());
			item.setCooperatorName(obj[4].toString());
			item.setCreaterTime(obj[17].toString());
			item.setCreator(obj[18]==null?"":obj[18].toString());
			item.setEndDate(obj[5].toString());
			item.setId(id);
			item.setModifier(obj[20]==null?"":obj[20].toString());
			item.setModifyTime(obj[19].toString());
			item.setOwnerBody(obj[6].toString());
			item.setOwnerType(Integer.valueOf(obj[7].toString()));
			String pdfPath = (obj[8]==null||StringUtil.isBlank(obj[8].toString()))?"":appConfig.getPdfPathDomain()+obj[8].toString();
			String pdfName = "".equals(pdfPath)?"":pdfPath.substring(pdfPath.lastIndexOf("/")+1, pdfPath.length());
			item.setPdfName(pdfName);
			item.setPdfPath(pdfPath);
			item.setPopMode(obj[9]==null?"":obj[9].toString());
			item.setRemark(obj[10]==null?"":obj[10].toString());
			item.setShoulder(obj[11]==null?"":obj[11].toString());
			item.setStartDate(obj[12].toString());
			item.setStatus(Integer.valueOf(obj[16].toString()));
			item.setSuitDepart(Integer.valueOf(obj[13].toString()));
			item.setSuitPlatform(obj[14]==null?"":obj[14].toString());
			item.setSuitProduct(obj[15]==null?"":obj[15].toString());
		}
		return item;
	}
	
	//保存或更新，根据id
	public Contract saveOrUpdate(ContractItem item, String userNick) {
		Contract contract = null;
		DateTime time = DateTime.now();
		if(item.getId()<=0) {
			contract = new Contract();
			contract.setContractType(item.getContractType());
			contract.setContractNo(getContractNo(item.getOwnerBody(), item.getContractType(), time));
			contract.setCreateTime(time);
			contract.setCreator(userNick);
		}else {
			contract = this.contractRepository.findOne(item.getId());
			if(contract==null)
				return null;
		}
		contract = save(item, userNick, contract, time);
		return contract;
	}
	
	//保存或更新，根据合同编号
	public boolean saveOrUpdateExcel(ContractItem item, String userNick) {
		Contract contract = null;
		DateTime time = DateTime.now();
		if(StringUtil.isBlank(item.getContractNo())) {
			contract = new Contract();
			contract.setContractType(item.getContractType());
			contract.setContractNo(getContractNo(item.getOwnerBody(), item.getContractType(), time));
			contract.setCreateTime(time);
			contract.setCreator(userNick);
		}else {
			contract = this.contractRepository.getByContractNo(item.getContractNo());
			if(contract==null)
				return false;
		}
		contract = save(item, userNick, contract, time);
		return true;
	}
	
	//保存
	public Contract save(ContractItem item, String userNick, Contract contract, DateTime time) {
		contract.setCooperateNo(item.getCooperateNo());
		contract.setCooperatorName(item.getCooperatorName());
		contract.setEndDate(item.getEndDate().replaceAll("/", "-"));
		contract.setModifier(userNick);
		contract.setModifyTime(time);
		contract.setOwnerBody(item.getOwnerBody());
		contract.setOwnerType(item.getOwnerType());
		if(StringUtil.isNotBlank(item.getPdfPath())) {
			contract.setPdfPath(item.getPdfPath().replaceAll(this.appConfig.getPdfPathDomain(), ""));
		}
		contract.setPopMode(item.getPopMode().replaceAll("/", ","));
		contract.setRemark(item.getRemark());
		contract.setShoulder(item.getShoulder());
		contract.setStartDate(item.getStartDate().replaceAll("/", "-"));
		contract.setSuitDepart(item.getSuitDepart());
		contract.setSuitPlatform(item.getSuitPlatform().replaceAll("/", ","));
		contract.setSuitProduct(item.getSuitProduct().replaceAll("/", ","));
		contract = this.contractRepository.save(contract);
		return contract;
	}
	
	//生成唯一合同编号
	public String getContractNo(String ownerBody, Integer contractType, DateTime time) {
		String year = time.getYear()+"";
		String num = getNumByYear(year, contractType)+"";
		if(num.length()<4) {
			String zero = "";
			for (int i = 0; i < 4-num.length(); i++) {
				zero+=0;
			}
			num = zero+num;
		}
		StringBuilder contractNo = new StringBuilder();
		contractNo.append(ownerBody);
		contractNo.append("-");
		if(contractType==1) {
			contractNo.append("J");
		}else {
			contractNo.append("Y");
		}
		contractNo.append("-");
		contractNo.append(year);
		contractNo.append(num);
		
		return contractNo.toString();
	}
	
	public int getNumByYear(String year,int contractType) {
		int num = 0;
		Object numObj = this.contractRepository.getNumByYear(year, contractType);
		if(numObj!=null&&StringUtil.isNotBlank(numObj.toString())) {
			num = Integer.valueOf(numObj.toString())+1;
		}
		return num==0?1:num;
	}
	
	public void updatePdfPath(Long id, String path, String userNick) {
		this.contractRepository.updatePdfPath(id ,path,userNick);
	}
	
	public void deleteById(long id, String userNick) {
		this.contractRepository.deleteById(id, userNick);
	}
	
	public List<String> getStrList(String str){
		if(StringUtil.isBlank(str))
			return null;
		String[] strs = str.split(",");
	    List<String> list = Lists.newArrayList();
	    for (String s:strs){
	    	if(StringUtil.isNotBlank(s)) 
	    		list.add(s);
        }
    	return list;
    }
	
	public List<Integer> getIntList(String str){
		if(StringUtil.isBlank(str))
			return null;
		String[] strs = str.split(",");
	    List<Integer> list = Lists.newArrayList();
	    for (String s:strs){
	    	if("-1".equals(s))
	    		return null;
	    	if(StringUtil.isNotBlank(s)) 
	    		list.add(Integer.valueOf(s));
        }
	    return list;
    }

	
	private static String[] customerTitle = new String[] {"合同编号","客户主体*","我方主体*","甲方主体*","合同开始日期*","合同结束日期*","合同状态","合同附件下载地址","合同负责人","合同适用部门*","适用平台","适用产品","推广模式","客户合同编号","备注","合同创建时间","合同创建人","最后一次操作时间","最后一次操作人"};
	private static String[] channelTitle  = new String[] {"合同编号","渠道主体*","我方主体*","甲方主体*","合同开始日期*","合同结束日期*","合同状态","合同附件下载地址","合同负责人","合同适用部门*","适用平台","适用产品","推广模式","渠道合同编号","备注","合同创建时间","合同创建人","最后一次操作时间","最后一次操作人"};;
	private static String explain = "导入必看：\r\n" + 
			"1、标*的字段为导入必填字段；\r\n" + 
			"2、我方主体全称（六选一）：深圳康远互动科技有限公司、霍尔果斯康远互动网络科技有限公司、上海贝玩网络科技有限公司、深圳自由泰格互动科技有限公司、北京康远互动网络科技有限公司、上海贝玩文化传播有限公司\r\n" + 
			"3、日期格式：YYYY/MM/DD。例如：2019/01/01；\r\n" + 
			"4、合同适用部门（三选一）：商店分发、信息流、信息流/商店分发。例如：信息流/商店分发；\r\n" + 
			"5、适用平台：信息流或商店分发-平台名称。如有多个选项，请用‘/’分隔。例如信息流-wifi/信息流-猎豹        \r\n" + 
			"6、推广模式：CPA、CPD、CPM、CPC、CPS、CPT、CPPA。如有多个选项，请用‘/’分隔。例如:CPA/CPC；\r\n" + 
			"7、合同编号系统自动生成，不可修改\r\n" + 
			"8、甲方主体需要从客户/渠道/我方主体中选择";
	*//**
	 * 生成excel文件流
	 * @param response
	 * @return
	 *//*
	@SuppressWarnings("deprecation")
	public InputStream writeExcel(ContractResponse response, Integer contractType) {
		// 创建表格
		@SuppressWarnings("resource")
		Workbook wb = new HSSFWorkbook();// xls
		Sheet sheet = null;
		if(contractType==1) {
			sheet = wb.createSheet("客户合同");
		}else {
			sheet = wb.createSheet("渠道合同");
		}
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 18));  
	    
		//设置表头样式
		CellStyle style = wb.createCellStyle();
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
		style.setAlignment(CellStyle.ALIGN_LEFT);// 水平左对齐
		style.setWrapText(true);// 指定当单元格内容显示不下时自动换行
		style.setFillBackgroundColor(HSSFColor.YELLOW.index);
		style.setFillForegroundColor(HSSFColor.YELLOW.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		//字体样式
	    Font fontTitle = wb.createFont();
        fontTitle.setFontHeightInPoints((short)12);//大小
        fontTitle.setColor(Font.COLOR_RED);
        fontTitle.setBold(true);
        style.setFont(fontTitle);

		//创建表头
		Row row = sheet.createRow(0);
		row.setHeightInPoints(150);
		Cell cell = row.createCell(0);//第一行第一列 为表头
		cell.setCellValue(explain);
		cell.setCellStyle(style);
		
		//设置标题样式
		CellStyle style1 = wb.createCellStyle();
		style1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
		style1.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中
		style1.setWrapText(true);// 指定当单元格内容显示不下时自动换行
	    Font font = wb.createFont();
        font.setFontHeightInPoints((short)12);//大小
        style1.setFont(font);
		// 创建第二行(列字段名称)并设置单元格的格式
		row = sheet.createRow(1);
		if (contractType == 1) {
			for (int i = 0; i < customerTitle.length; i++) {
				cell = row.createCell(i);
				cell.setCellValue(customerTitle[i]);
				cell.setCellStyle(style1); // 样式，居中
			}
		} else {
			for (int i = 0; i < channelTitle.length; i++) {
				cell = row.createCell(i);
				cell.setCellValue(channelTitle[i]);
				cell.setCellStyle(style1); // 样式，居中
			}
		}

		List<ContractItem> list = Lists.newArrayList();
		if (response != null)
			list = response.getList();

		// 写入数据 从第三行开始
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 2);
			ContractItem item = list.get(i);
			row.createCell(0).setCellValue(item.getContractNo());
			row.createCell(1).setCellValue(item.getCooperatorName());
			row.createCell(2).setCellValue(InitConst.OwnerBody.getMsg(item.getOwnerBody()));
			if (item.getOwnerType() == 1) {
				row.createCell(3).setCellValue(InitConst.OwnerBody.getMsg(item.getOwnerBody()));
			} else {
				row.createCell(3).setCellValue(item.getCooperatorName());
			}
			row.createCell(4).setCellValue(item.getStartDate().replaceAll("-", "/"));
			row.createCell(5).setCellValue(item.getEndDate().replaceAll("-", "/"));
			row.createCell(6).setCellValue(InitConst.ContractNewStatus.getMsg(item.getStatus()));
			row.createCell(7).setCellValue(item.getPdfPath());
			row.createCell(8).setCellValue(item.getShoulder());
			row.createCell(9).setCellValue(InitConst.SuitDepart.getMsg(item.getSuitDepart()).replaceAll("A", "/"));
			row.createCell(10).setCellValue(item.getSuitPlatform().replaceAll(",", "/"));
			row.createCell(11).setCellValue(item.getSuitProduct().replaceAll(",", "/"));
			row.createCell(12).setCellValue(item.getPopMode().replaceAll(",", "/"));
			row.createCell(13).setCellValue(item.getCooperateNo());
			row.createCell(14).setCellValue(item.getRemark());
			row.createCell(15).setCellValue(item.getCreaterTime());
			row.createCell(16).setCellValue(item.getCreator());
			row.createCell(17).setCellValue(item.getModifyTime());
			row.createCell(18).setCellValue(item.getModifier());
		}
		//宽度自适应
		for (int i = 0; i < 19; i++) {
	        sheet.autoSizeColumn(i,true);
		}

		// 创建文件写入流，
		InputStream excelStream = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			wb.write(out);
			excelStream = new ByteArrayInputStream(out.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return excelStream;
	}

	*//**
	 * 上传excel文件到临时目录后并开始解析
	 * @param fileName
	 * @param contractItemReadList 
	 * @param file
	 * @param userName
	 * @return
	 *//*
	public String batchImport(String filePath, String fileName, List<ContractItem> contractItemReadList){

		File tempFile = new File(filePath + fileName);
		// 检测是否存在目录
		if (!tempFile.getParentFile().exists()) {
			tempFile.getParentFile().mkdirs();
		}

		// 初始化输入流
		InputStream is = null;
		try {
			// 根据新建的文件实例化输入流
			is = new FileInputStream(tempFile);
			// 根据版本选择创建Workbook的方式
			Workbook wb = null;
			// 根据文件名判断文件是2003版本还是2007版本
			if (fileName.toLowerCase().endsWith(".xlsx")) {
				wb = new XSSFWorkbook(is);
			} else if(fileName.toLowerCase().endsWith(".xls")){
				wb = new HSSFWorkbook(is);
			} else {
				return "不是excel文件，请选择excel格式";
			}
			// 根据excel里面的内容读取知识库信息
			return readExcelValue(wb, contractItemReadList);
		} catch (IOException e) {
			e.printStackTrace();
			return "读取excel文件异常，请稍后重试:{}"+e.getMessage();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					is = null;
					e.printStackTrace();
				}
			}
			// 删除上传的临时文件
			if (tempFile.exists()) {
				tempFile.delete();
			}
		}
	}
	
	
	*//**
	 * 解析Excel里面的数据
	 * 
	 * @param wb
	 * @param contractItemReadList 
	 * @return
	 *//*
	private String readExcelValue(Workbook wb, List<ContractItem> contractItemReadList) {
		// 错误信息接收器
		String errorMsg = "";
		// 得到第一个shell
		Sheet sheet = wb.getSheetAt(0);
		// 得到Excel的行数
		int totalRows = sheet.getPhysicalNumberOfRows();
		// 总列数
		int totalCells = 0;
		// 得到Excel的列数(前提是有行数)，从第一行算起
		if (totalRows >= 1 && sheet.getRow(1) != null) {
			totalCells = sheet.getRow(1).getPhysicalNumberOfCells();
		}
		ContractItem item = null;

		// 循环Excel行数,从第二行开始。标题不入库
		for (int r = 2; r < totalRows; r++) {
			Row row = sheet.getRow(r);
			if (row == null) 
				continue;

			item = new ContractItem();
			// 循环Excel的列
			for (int c = 0; c < totalCells; c++) {
				Cell cell = row.getCell(c);
				
				if(c==0) 
					item.setContractNo(cellFormat2String(cell));;
				if(c==1) 
					item.setCooperatorName(cellFormat2String(cell));
				if(c==2) 
					item.setOwnerBody(InitConst.OwnerBody.getType(cellFormat2String(cell)));
				if(c==3) {
					String ownerBody = InitConst.OwnerBody.getMsg(item.getOwnerBody());
					String cooperatorName = item.getCooperatorName();
					if(ownerBody.equals(cellFormat2String(cell))) {
						item.setOwnerType(1);
					}else if(cooperatorName.equals(cellFormat2String(cell))) {
						item.setOwnerType(0);
					}else if(StringUtil.isBlank(cellFormat2String(cell))){
						item.setOwnerType(null);
					}else {
						item.setOwnerType(-1);
					}
				}
				if(c==4) 
					item.setStartDate(cellFormat2String(cell));;
				if(c==5)
					item.setEndDate(cellFormat2String(cell));
				if(c==8) 
					item.setShoulder(cellFormat2String(cell));;
				if(c==9)
					item.setSuitDepart(InitConst.SuitDepart.getType(cellFormat2String(cell).replace("/", "A")));
				if(c==10) 
					item.setSuitPlatform(cellFormat2String(cell));;
				if(c==11)
					item.setSuitProduct(cellFormat2String(cell));;
				if(c==12) 
					item.setPopMode(cellFormat2String(cell));;
				if(c==13)
					item.setCooperateNo(cellFormat2String(cell));;
				if(c==14) 
					item.setRemark(cellFormat2String(cell));;
			}
			item.setExcelLine(r+1);
			contractItemReadList.add(item);
		}
		return errorMsg;
	}

	@SuppressWarnings("deprecation")
	public String cellFormat2String(Cell cell) {
		String cellValue = "";
		if (null != cell) {
			// 以下是判断数据的类型
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_NUMERIC: // 数字
				// 判断是否为日期类型
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					// 用于转化为日期格式
					Date d = cell.getDateCellValue();
					DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
					cellValue = formater.format(d);
				} else {
					// 用于格式化数字，只保留数字的整数部分
					DecimalFormat df = new DecimalFormat("#.##");
					cellValue = df.format(cell.getNumericCellValue());
				}
				break;
			case HSSFCell.CELL_TYPE_STRING: // 字符串
				cellValue = cell.getStringCellValue();
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
				cellValue = cell.getBooleanCellValue() + "";
				break;
			case HSSFCell.CELL_TYPE_FORMULA: // 公式
				cellValue = cell.getCellFormula() + "";
				break;
			case HSSFCell.CELL_TYPE_BLANK: // 空值
				cellValue = "";
				break;
			case HSSFCell.CELL_TYPE_ERROR: // 故障
				cellValue = "";
				break;
			default:
				cellValue = "";
				break;
			}
		}
		return cellValue;
	}

}
*/